package com.party.mobile.web.controller.activity;

import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.authorization.annotation.Authorization;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.BaseModel;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.ActStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.activity.ActivityWithMemberPartner;
import com.party.core.model.commune.CMemberInfo;
import com.party.core.model.counterfoil.Counterfoil;
import com.party.core.model.counterfoil.CounterfoilType;
import com.party.core.model.distributor.DistributorRelationType;
import com.party.core.model.gatherForm.GatherProject;
import com.party.core.model.member.*;
import com.party.core.model.order.OrderForm;
import com.party.core.model.order.OrderType;
import com.party.core.model.system.RoleEnum;
import com.party.core.model.system.RoleType;
import com.party.core.model.system.SysConfig;
import com.party.core.model.system.TargetType;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.commune.ICMemberInfoService;
import com.party.core.service.counterfoil.ICounterfoilService;
import com.party.core.service.member.*;
import com.party.core.service.member.biz.MemberPersonalCountBizService;
import com.party.core.service.order.IOrderFormService;
import com.party.core.service.system.ISysConfigService;
import com.party.core.service.system.ISysRoleService;
import com.party.mobile.biz.activity.ActivityBizService;
import com.party.mobile.biz.activity.MemberActBizService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.biz.distributor.DistributorBizService;
import com.party.mobile.biz.member.CIntegralBizToService;
import com.party.mobile.biz.member.MemberBizService;
import com.party.mobile.web.annotation.SessionToken;
import com.party.mobile.web.annotation.VisitCollect;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.activity.input.ApplyInput;
import com.party.mobile.web.dto.activity.input.ListInput;
import com.party.mobile.web.dto.activity.output.*;
import com.party.mobile.web.dto.crowdfund.input.StatisticsInput;
import com.party.mobile.web.dto.distributor.input.GetDistributorInput;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.mobile.web.dto.login.output.MemberOutput;
import com.party.mobile.web.interceptor.TokenInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Nullable;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 活动控制层
 * party
 * Created by wei.li
 * on 2016/9/23 0023.
 */

@Controller
@RequestMapping(value = "/activity/activity")
public class ActivityController {

    @Autowired
    private IActivityService activityService;

    @Autowired
    private IMemberActService memberActService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private MemberBizService memberBizService;

    @Autowired
    private ActivityBizService activityBizService;

    @Autowired
    private MemberActBizService memberActBizService;

    @Autowired
    private CurrentUserBizService currentUserBizService;

    @Autowired
    private IOrderFormService orderFormService;

    @Autowired
    private DistributorBizService distributorBizService;

    @Autowired
    private ICounterfoilService counterfoilService;

    @Autowired
    private MemberPersonalCountBizService memberPersonalCountBizService;

    @Autowired
    private IPartnerMemberService partnerMemberService;

    @Resource
    private TokenInterceptor tokenInterceptor;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private IMemberGroupService memberGroupService;

    @Autowired
    private IMemberGroupPermissionService memberGroupPermissionService;

    @Autowired
    private ICMemberInfoService cMemberInfoService;

    protected static Logger logger = LoggerFactory.getLogger(ActivityController.class);


    /**
     * 分页查询活动列表
     *
     * @param listInput 查询参数
     * @param page      分页参数
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "/list")
    @VisitCollect(module = TargetType.ACTIVITY)
    public AjaxResult list(ListInput listInput, Page page) {
        List<ListOutput> listOutputList = activityBizService.list(listInput, page);
        return AjaxResult.success(listOutputList, page);
    }

    /**
     * 获取活动详情
     *
     * @param id 活动主键
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "/getDetails")
    @VisitCollect(module = TargetType.ACTIVITY)
    public AjaxResult getDetails(String id, HttpServletRequest request) {

        //数据验证
        if (Strings.isNullOrEmpty(id)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "活动主键不能为空");
        }

        //查询活动
        Activity activity = activityService.get(id);
        if (null == activity || activity.getDelFlag().equals("1")) {
            return AjaxResult.error(PartyCode.IS_NO_DATA, "活动不存在");
        }

        try {
            ActivityOutput activityOutput = activityBizService.get(activity, request);

            AjaxResult ajaxResult = AjaxResult.success(activityOutput);
            tokenInterceptor.getToken(ajaxResult);
            return ajaxResult;
        } catch (Exception e) {
            logger.error("获取活动详情异常", e);
            return AjaxResult.error(100, "获取活动详情异常");
        }
    }


    /**
     * web活动效果
     * 显示获取活动详情
     *
     * @param id 活动主键
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "/getDetail")
    public AjaxResult getDetail(String id, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult(true);
        //数据验证
        if (Strings.isNullOrEmpty(id)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "活动主键不能为空");
        }

        //查询活动
        Activity activity = activityService.get(id);
        if (null == activity || activity.getDelFlag().equals("1")) {
            return AjaxResult.error(PartyCode.IS_NO_DATA, "活动不存在");
        }

        try {
            ActivityOutput activityOutput = activityBizService.get(activity, request);
            ajaxResult.setData(activityOutput);
            tokenInterceptor.getToken(ajaxResult);
            return ajaxResult;
        } catch (Exception e) {
            logger.error("获取活动详情异常", e);
            return AjaxResult.error(100, "未知异常");
        }
    }

    /**
     * 获取活动报名列表
     *
     * @param id 活动主键
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "/getActMember")
    public AjaxResult getActMember(String id, Page page, HttpServletRequest request) {
        WithBuyer withBuyer = new WithBuyer();
        withBuyer.setActId(id);
        List<WithBuyer> withBuyerList = memberActService.withBuyerList(withBuyer, page);
        List<BuyerOutput> buyerOutputList = LangUtils.transform(withBuyerList, new Function<WithBuyer, BuyerOutput>() {
            @Nullable
            @Override
            public BuyerOutput apply(@Nullable WithBuyer withBuyer) {
                return BuyerOutput.transform(withBuyer);
            }
        });
        return AjaxResult.success(buyerOutputList, page);
    }

    /**
     * 分销活动详情
     *
     * @param input   输入参数
     * @param request 请求参数
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "distribution/details")
    @VisitCollect(module = TargetType.ACTIVITY)
    public AjaxResult getDistributionDetails(GetDistributorInput input, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();
        //数据验证
        if (Strings.isNullOrEmpty(input.getTargetId())) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "活动主键不能为空");
        }

        //查询活动
        Activity activity = activityService.get(input.getTargetId());
        if (null == activity || activity.getDelFlag().equals("1")) {
            return AjaxResult.error(PartyCode.IS_NO_DATA, "活动不存在");
        }
        ActivityOutput activityOutput;
        try {
            activityOutput = activityBizService.getDistributionDetails(activity, input, request);
        } catch (BusinessException be) {
            ajaxResult.setErrorCode(be.getCode());
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        }

        ajaxResult.setSuccess(true);
        ajaxResult.setData(activityOutput);
        return ajaxResult;
    }


    /**
     * 活动是否报名
     *
     * @param id 活动id
     * @return 交互数据
     */
    @ResponseBody
    @Authorization
    @RequestMapping("/isApply")
    public AjaxResult isApply(String id, HttpServletRequest request) {

        //数据验证
        if (Strings.isNullOrEmpty(id)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "活动编号不能为空");
        }
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);

        //是否报名
        MemberAct memberAct = memberActService.getMyAct(currentUser.getId(), id);
        if (null != memberAct) {
            ApplyOutput applyOutput = new ApplyOutput();
            applyOutput.setMemberActId(memberAct.getId());
            applyOutput.setActStatus(memberAct.getCheckStatus());
            return AjaxResult.success(applyOutput);
        }
        return AjaxResult.success();
    }

    /**
     * 签到
     *
     * @param hdId
     * @param request
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "/signIn")
    public AjaxResult signIn(String hdId, HttpServletRequest request) {
        if (Strings.isNullOrEmpty(hdId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "活动编号不能为空");
        }
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);

        // 是否报名
        MemberAct memberAct = memberActService.getMyAct(currentUser.getId(), hdId);
        if (memberAct == null || memberAct.getJoinin().equals(YesNoStatus.NO.getCode())) {
            return AjaxResult.error(100, "还没有报名");
        }
        if (memberAct != null) {
            if (memberAct.getCheckStatus().equals(ActStatus.ACT_STATUS_PAID.getCode())) {
                // 已支付 直接签到
                memberAct.setSignin(YesNoStatus.YES.getCode());
                memberActService.update(memberAct);
                return AjaxResult.success();
            } else if (memberAct.getCheckStatus().equals(ActStatus.ACT_STATUS_AUDIT_PASS.getCode())) {
                OrderForm orderForm = orderFormService.get(memberAct.getOrderId());
                // 待支付 转向付款
                return AjaxResult.error(orderForm.getId(), 101, "还没有支付");
            } else if (memberAct.getCheckStatus().equals(ActStatus.ACT_STATUS_AUDITING.getCode())) {
                // 未审核 提示审核 转向我的活动参与
                return AjaxResult.error(102, "还没有审核");
            }
        }
        return null;
    }


    /**
     * 活动报名
     *
     * @param applyInput 报名输入视图
     * @return 交互数据
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "/apply")
    public AjaxResult apply(@Validated ApplyInput applyInput, BindingResult result, HttpServletRequest request) {

        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }
        try {
            CurrentUser currentUser = memberBizService.bindPhoneBiz(applyInput.getMobile(), applyInput.getVerifyCode(), request);

            //如果字段为空 更新必要的用户信息
            Member curMember = memberBizService.updateImportantInfo(ApplyInput.transformMember(applyInput), memberService.get(currentUser.getId()));
            MemberOutput memberOutput = memberBizService.getLoginMember(curMember);

            ApplyOutput applyOutput = memberActBizService.getApplyData(currentUser.getId(), applyInput);

            Map map = new HashMap();
            map.put("order", applyOutput);
            map.put("member", memberOutput);

            return AjaxResult.success(map);
        } catch (BusinessException e) {
            return AjaxResult.error(e.getCode(), e.getMessage());
        }

    }

    /**
     * 活动报名
     *
     * @param applyInput 报名输入视图
     * @return 交互数据
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "/apply2")
    public AjaxResult apply2(@Validated ApplyInput applyInput, BindingResult result, HttpServletRequest request) {

        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }

        Activity activity = activityService.get(applyInput.getId());
        if (activity == null) {
            return AjaxResult.error(PartyCode.DATA_IS_BE_DELETE, "活动不存在");
        }

        try {
            CurrentUser currentUser = memberBizService.bindPhoneBiz(applyInput.getMobile(), applyInput.getVerifyCode(), request);

            //如果字段为空 更新必要的用户信息
            Member curMember = memberBizService.updateImportantInfo(ApplyInput.transformMember(applyInput), memberService.get(currentUser.getId()));
            MemberOutput memberOutput = memberBizService.getLoginMember(curMember);

            ApplyOutput applyOutput = memberActBizService.getApplyData2(currentUser.getId(), applyInput);

            Map map = new HashMap();
            map.put("order", applyOutput);
            map.put("member", memberOutput);

            return AjaxResult.success(map);
        } catch (BusinessException e) {
            return AjaxResult.error(e.getCode(), e.getMessage());
        }
    }

    /**
     * 活动报名
     *
     * @param applyInput 报名输入视图
     * @return 交互数据
     */
    @SessionToken(verify = true)
    @ResponseBody
    @Authorization
    @RequestMapping(value = "/apply3")
    public AjaxResult apply3(@Validated ApplyInput applyInput, BindingResult result, HttpServletRequest request, GatherProject project) {
        try {
            // 数据验证
            if (result.hasErrors()) {
                List<ObjectError> allErrors = result.getAllErrors();
                String description = allErrors.get(0).getDefaultMessage();
                throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, description);
            }

            if (StringUtils.isEmpty(applyInput.getCounterfoilId())) {
                throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, "没有票据ID");
            }

            Counterfoil counterfoil = counterfoilService.get(applyInput.getCounterfoilId());
            if (null == counterfoil) {
                throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, "票据不存在");
            } else {
                //票种数量
                int limitNumDb = counterfoil.getLimitNum();
                //已购数量
                int joinNumDb = counterfoil.getJoinNum();
                if (limitNumDb == joinNumDb) {
                    throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, "该票种已卖完");
                }
            }

            CurrentUser currentUser = memberBizService.bindPhoneBiz2(applyInput.getMobile(), applyInput.getVerifyCode(),
                    applyInput.getCountryCode(), request);

            //如果字段为空 更新必要的用户信息
            Member curMember = memberBizService.updateImportantInfo(ApplyInput.transformMember(applyInput), memberService.get(currentUser.getId()));
            MemberOutput memberOutput = memberBizService.getLoginMember(curMember);

            applyInput.setOrderType(OrderType.ORDER_ACTIVITY.getCode());
            ApplyOutput applyOutput = memberActBizService.getApplyData4(currentUser.getId(), applyInput, project, counterfoil);
            CMemberInfo cMemberInfoOrg = cMemberInfoService.getByMemberId(curMember.getId());
            if (cMemberInfoOrg != null) {
                if (CMemberInfo.CHECK_STATUS_REJECT.equals(cMemberInfoOrg.getCheckStatus()))
                {
                    cMemberInfoOrg.setCheckStatus(CMemberInfo.CHECK_STATUS_AWAIT);
                    cMemberInfoService.update(cMemberInfoOrg);
                }
            } else {
                cMemberInfoOrg = new CMemberInfo();
                cMemberInfoOrg.setMemberId(curMember.getId());
                cMemberInfoOrg.setCheckStatus(CMemberInfo.CHECK_STATUS_AWAIT);
                cMemberInfoService.insert(cMemberInfoOrg);
            }
            Map map = new HashMap();
            map.put("order", applyOutput);
            map.put("member", memberOutput);

            return AjaxResult.success(map);
        } catch (BusinessException e) {
            logger.error("活动报名异常", e);
            AjaxResult ajaxResult = new AjaxResult();
            tokenInterceptor.getToken(ajaxResult);
            ajaxResult.setData(applyInput.getId());
            ajaxResult.setErrorCode(e.getCode());
            ajaxResult.setDescription(e.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            logger.error("活动报名异常", e);
            AjaxResult ajaxResult = new AjaxResult();
            tokenInterceptor.getToken(ajaxResult);
            ajaxResult.setData(applyInput.getId());
            ajaxResult.setDescription(e.getMessage());
            return ajaxResult;
        }
    }

    /**
     * 取消报名
     *
     * @param memberActId 活动报名编号
     * @return 交互数据
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "/cancel")
    public AjaxResult cancel(String memberActId, HttpServletRequest request) {

        //数据验证
        if (Strings.isNullOrEmpty(memberActId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "报名编号不能为空");
        }

        try {
            ApplyOutput applyOutput = memberActBizService.joinCancel(memberActId, request);
            Map<String, Object> map = memberActBizService.getCancelInfo(memberActId, applyOutput);
            return AjaxResult.success(map);
        } catch (BusinessException be) {
            return AjaxResult.error(be.getCode(), be.getMessage());
        }
    }

    /**
     * 取消报名
     *
     * @param memberActId 活动报名编号
     * @return 交互数据
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "/distributorCancel")
    public AjaxResult distributorCancel(String memberActId, String distributorId, String parentId, HttpServletRequest request) {

        //数据验证
        if (Strings.isNullOrEmpty(memberActId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "报名编号不能为空");
        }

        try {
            ApplyOutput applyOutput = memberActBizService.joinCancel(memberActId, request);
            MemberAct memberAct = memberActService.get(memberActId);
            Activity activity = activityService.get(memberAct.getActId());
            Map<String, Object> map = memberActBizService.getCancelInfo(memberActId, applyOutput);
            // 是否是自己的分销
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            boolean isMyDistributor
                    = distributorBizService.isMyDistribution(currentUser, DistributorRelationType.ACTIVITY.getCode(),
                    activity.getId(), distributorId, parentId);

            map.put("isMyDistribution", isMyDistributor);
            return AjaxResult.success(map);
        } catch (BusinessException be) {
            return AjaxResult.error(be.getCode(), be.getMessage());
        }
    }

    /**
     * 活动凭证接口
     *
     * @param memberActId 活动报名id
     * @param request
     * @return 活动凭证交互数据
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "/evidence")
    public AjaxResult evidence(String memberActId, HttpServletRequest request) {
        //数据验证
        if (Strings.isNullOrEmpty(memberActId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "报名编号不能为空");
        }

        RegisterCertificateOutput registerCertificateOutput = null;
        try {
            registerCertificateOutput = memberActBizService.getRegisterCertification(memberActId, request);
        } catch (BusinessException be) {
            return AjaxResult.error(be.getCode(), be.getMessage());
        }

        return AjaxResult.success(registerCertificateOutput);
    }

    /**
     * 分页查询发布的活动列表
     *
     * @param page 分页参数
     * @return 交互数据
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/publishList")
    public AjaxResult publishList(Page page, HttpServletRequest request) {
        try {
            String title = "";
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
//            MemberGroup member = memberGroupService.get(currentUser.getId());
//            String loginName = member.getUsername();
            String memeberId = currentUser.getId();
            // todo 临时使用的代码 后面不用了就把删除掉
//            if (StringUtils.isNotEmpty(loginName) && loginName.contains("XZGS_")) {
//                if (loginName.contains(Constant.ZH_XZGS_JX)) {
//                    title = "健行分社";
//                } else if (loginName.contains(Constant.ZH_XZGS_QL)) {
//                    title = "麒麟分社";
//                } else if (loginName.contains(Constant.ZH_XZGS_YJ)) {
//                    title = "赢家分社";
//                }
//
//                //获取行知公社参数配置
//                SysConfig xzgsConfig = sysConfigService.findByCode("XZGSID");
//                if (xzgsConfig == null) {
//                    //正式环境中行知公社机构ID
//                    memeberId = "c94e89415d7d4611b706cecfc43af2ae";
//                } else {
//                    memeberId = xzgsConfig.getValue();
//                }
//            }

            Map<String, Object> params = Maps.newHashMap();
            List<String> orgIds = Lists.newArrayList();
            boolean isTwoChild = sysRoleService.hasRole(currentUser.getId(), RoleEnum.BRANCH_TEAM_LEADER.getCode());
            if (isTwoChild) {
                List<String> targetIds = Lists.newArrayList();
                MemberGroup memberGroup = memberGroupService.get(currentUser.getId());
                Integer isShowAll = memberGroupPermissionService.getIsShowAll(TargetType.ACTIVITY.getCode(), currentUser.getId(), memberGroup.getPartnerId(), targetIds);
                if (null == isShowAll) {
                    return AjaxResult.success(new ArrayList<ActivityOutput>(), page);
                } else if (YesNoStatus.NO.getCode().equals(isShowAll)) {
                    params.put("ids", targetIds);
                    orgIds.add(memberGroup.getPartnerId());
                } else {
                    orgIds.add(memberGroup.getPartnerId());
                }
            }

            ActivityWithMemberPartner activity = new ActivityWithMemberPartner();
            activity.setMember(memeberId);
            activity.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
            activity.setIsCrowdfunded(0);
            activity.setTitle(title);
            List<ActivityOutput> activityOutputs = activityBizService.publishList(page, request, activity, orgIds, params);
            return AjaxResult.success(activityOutputs, page);
        } catch (Exception e) {
            logger.error("获取我发布的活动列表异常", e);
            return AjaxResult.error(100, "获取我发布的活动列表异常");
        }
    }


    /**
     * 行知公社分页查询发布的活动列表
     *
     * @param page 分页参数
     * @return 交互数据
     */
    //@Authorization
    @ResponseBody
    @RequestMapping(value = "/kcPublishList")
    public AjaxResult kcPublishList(HttpServletRequest request, Page page) {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        if (currentUser == null) {
            String memeberId = null;
            //获取行知公社参数配置
            SysConfig xzgsConfig = sysConfigService.findByCode("XZGSID");
            if (xzgsConfig == null) {
                //正式环境中行知公社机构ID
                memeberId = "c94e89415d7d4611b706cecfc43af2ae";
            } else {
                memeberId = xzgsConfig.getValue();
            }
            ActivityWithMemberPartner activity = new ActivityWithMemberPartner();
            activity.setMember(memeberId);
            activity.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
            activity.setIsCrowdfunded(0);
            List<ActivityOutput> activityOutputs = activityBizService.publishList(page, null, activity, null, null);
            return AjaxResult.success(activityOutputs, page);
        } else {
            try {
                SysConfig xzgsConfig = sysConfigService.findByCode("XZGSID");
                String partnerId = "";
                if (xzgsConfig == null) {
                    //正式环境中行知公社机构ID
                    partnerId = "c94e89415d7d4611b706cecfc43af2ae";
                } else {
                    partnerId = xzgsConfig.getValue();
                }
                List<String> orgIds = memberGroupService.getChildWithMy(partnerId);
                List<String> partenrIds = new ArrayList<>();
                PartnerMember mainOrg = partnerMemberService.getMainOrg(currentUser.getId(), partnerId);
                if (mainOrg != null) {
                    partenrIds.add(mainOrg.getPartnerId());
                }

                ActivityWithMemberPartner activity = new ActivityWithMemberPartner();
                //设置活动发布者
                activity.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
                activity.setIsCrowdfunded(0);

                List<ActivityOutput> activityOutputs = new ArrayList<>();
                if (partenrIds.contains(partnerId) && partenrIds.size() == 1) {
                    activityOutputs = activityBizService.publishList(page, null, activity, orgIds, null);
                } else {
                    activityOutputs = activityBizService.publishList(page, null, activity, partenrIds, null);
                }

                return AjaxResult.success(activityOutputs, page);
            } catch (Exception e) {
                logger.error("行知公社获取我的活动列表异常", e);
                return AjaxResult.error(100, "行知公社获取我的活动列表异常");
            }
        }

    }


    /**
     * 分页查询发布的众筹活动列表
     *
     * @param page 分页参数
     * @return 交互数据
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/publishZcActivityList")
    public AjaxResult publishZcActivityList(Page page, HttpServletRequest request) {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        ActivityWithMemberPartner activity = new ActivityWithMemberPartner();
        activity.setMember(currentUser.getId());
        activity.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        activity.setIsCrowdfunded(1);
        List<ActivityOutput> activityOutputs = activityBizService.publishList(page, request, activity, null, null);
        return AjaxResult.success(activityOutputs, page);
    }

    @Autowired
    private CIntegralBizToService integralBizToService;

    /**
     * 分页查询发布的活动的报名列表
     *
     * @param page 分页参数
     * @return 交互数据
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/actMemberList")
    public AjaxResult actMemberList(String hdId, Page page, HttpServletRequest request) {
        // 数据验证
        if (Strings.isNullOrEmpty(hdId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "活动主键不能为空");
        }
        try {
            // 获取当前登录的机构所拥有的角色
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            //是否拥有行知公社权限
            boolean isCommune = integralBizToService.isXZGSJurisdiction(currentUser.getId());

            MemberGroup memberGroup = memberGroupService.get(currentUser.getId());
            if (!isCommune && StringUtils.isNotEmpty(memberGroup.getPartnerId())) {
                isCommune  = sysRoleService.hasRole(memberGroup.getPartnerId(), RoleEnum.ONE_LEVEL_CHILD.getCode());
            }

            List<MemberActOutput> memberOutputs = activityBizService.actMemberList(page, hdId);

            for (MemberActOutput memberOutput : memberOutputs) {
                memberOutput.setKnowingCommune(isCommune);
            }

            return AjaxResult.success(memberOutputs, page);
        } catch (Exception e) {
            logger.error("获取活动报名列表异常", e);
            return AjaxResult.error(100, "活动的报名列表异常");
        }
    }

    /***
     * 标记会员是否参与
     * @Date 10:21 2019/10/9
     * @param id
     * @param request
     * @return
     **/
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/markJoinMember")
    public AjaxResult markJoinMember(String id, String joinRemarks, HttpServletRequest request) {
        // 数据验证
        if (Strings.isNullOrEmpty(id)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "活动参与人主键不能为空");
        }

        //验证备注数据长度
        if (StringUtils.isNotEmpty(joinRemarks)) {
            if (joinRemarks.length() > 200) {
                return AjaxResult.error(Integer.valueOf(9999), "字符超过200了！");
            }
        }

        boolean isFlag = activityBizService.updateMemberActByMemberId(id, joinRemarks);
        if (!isFlag) {
            return AjaxResult.error(Integer.valueOf(9999), "标记失败");
        }

        return AjaxResult.success();
    }

    @Authorization
    @ResponseBody
    @RequestMapping(value = "verify")
    public AjaxResult verify(Integer checkStatus, String targetId) {
        if (StringUtils.isNotEmpty(targetId)) {
            MemberAct entity = memberActService.get(targetId);
            if (null == entity || (entity.getCheckStatus() > ActStatus.ACT_STATUS_PAID.getCode())) {
                String strTips = "";
                if (entity.getCheckStatus().equals(ActStatus.ACT_STATUS_CANCEL.getCode())) {
                    strTips = "当前会员报名状态:已取消;不能继续审核";
                } else {
                    strTips = "当前会员报名状态:未参与;不能继续审核";
                }
                return new AjaxResult(false, strTips);
            }

            boolean flag = true;
            if (checkStatus.equals(ActStatus.ACT_STATUS_AUDIT_PASS.getCode())) {
                // 新的处理方式 免费的活动不生成订单
                if (entity.getCounterfoilType().equals(CounterfoilType.TYPE_FREE.getCode()) ||
                        entity.getCounterfoilType().equals(CounterfoilType.TYPE_OFF_LINE.getCode())) {
                    flag = memberActBizService.verifyPassFree(entity.getId(), entity.getActId());
                } else {
                    flag = memberActBizService.verifyPassNoFree(entity.getId(), entity.getActId());
                }
            } else if (checkStatus.equals(ActStatus.ACT_STATUS_AUDIT_REJECT.getCode())) {
                // 新的处理方式 免费的活动不生成订单
                if (entity.getCounterfoilType().equals(CounterfoilType.TYPE_FREE.getCode()) ||
                        entity.getCounterfoilType().equals(CounterfoilType.TYPE_OFF_LINE.getCode())) {
                    flag = memberActBizService.verifyFailFree(entity.getId(), entity.getActId());
                } else {
                    flag = memberActBizService.verifyFailNoFree(entity.getId());
                }
            }
            if (flag) {
                return AjaxResult.success("审核成功");
            } else {
                return AjaxResult.error(10000, "审核失败");
            }
        }
        return AjaxResult.error(10000, "审核失败");
    }

    /**
     * 线下付款 手动设置已付款
     *
     * @param memberAct
     * @return
     */
    @ResponseBody
    @RequestMapping("verify2")
    public AjaxResult verify2(MemberAct memberAct) {
        if (StringUtils.isNotEmpty(memberAct.getId())) {
            MemberAct dbMemberAct = memberActService.get(memberAct.getId());
            dbMemberAct.setRemarks(memberAct.getRemarks());
            dbMemberAct.setPayStatus(MemberAct.PAY_STATUS_YES);
            memberActService.update(dbMemberAct);

            try {
                String actId = dbMemberAct.getActId();
                Activity act = activityService.get(actId);
//                memberPersonalCountBizService.updateActivityNumMoney(act.getMember(), dbMemberAct.getMemberId(), dbMemberAct.getPayment(), true);
                PartnerMember partnerMember = partnerMemberService.findByPartnerAndMember(act.getMember(), dbMemberAct.getMemberId());
                memberPersonalCountBizService.countOne(partnerMember);
            } catch (Exception e) {
                logger.error("实时更新个人统计活动数量/金额异常", e);
            }

            return AjaxResult.success("审核成功");
        }
        return AjaxResult.error(10000, "审核失败");
    }

    /**
     * 统计
     *
     * @param input  输入视图
     * @param result 验证参数
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "statistics")
    public AjaxResult statistics(@Validated StatisticsInput input, BindingResult result) {
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }
        if (StringUtils.isNotEmpty(input.getApplyId())) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "报名id不能为空");
        }

        try {
            distributorBizService.statisticsOrder(input);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("分销统计报名数据异常", e);
            return AjaxResult.error(100, "分销统计报名数据异常");
        }
    }
}
